package server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

import org.json.JSONObject;

public class AMServerImpl extends UnicastRemoteObject implements IAMServer,	Serializable {

	private static final long serialVersionUID = 8946133393136230793L;

	protected AMServerImpl() throws RemoteException {
		super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());
	}

	@Override
	public boolean mount(String volumePath, String mountPoint, String fileSystem, String key, String keyfilePath) throws RemoteException {
		boolean result = false;

		// TODO Escape strings

		String[] script = new String[]{"bash","-c", "truecrypt --filesystem="+fileSystem+" \""+volumePath+"\" \""+mountPoint+"\" > /home/dradoslav/out 2>&1 <<EOF\n"+key+"\n\n\nEOF\n"};

		try {
			Runtime.getRuntime().exec(script);

			// TODO replace the sleep with a better method
			Thread.sleep(2000);

			// check if now the mountpoint exists
			String currentMountpoints = this.getMountpoints();

			if (currentMountpoints.contains("\""+mountPoint+"\"")) result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public boolean unmount(String mountPoint) throws RemoteException {
		boolean result = false;

		String[] script = new String[]{"bash","-c", "truecrypt -d \""+mountPoint+"\" > /home/dradoslav/out 2>&1"};

		try {
			Runtime.getRuntime().exec(script);

			// TODO replace the sleep with a better method
			Thread.sleep(2000);

			// check if now the mountpoint doesn't exist anymore
			String currentMountpoints = this.getMountpoints();

			if (!currentMountpoints.contains("\""+mountPoint+"\"")) result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public String getMountpoints() throws RemoteException {
		String filepath = "/etc/mtab";
//		String filepath = System.getProperty("user.dir")+"/examples/etcmtab";

		String result = "";

		try {
			// Open the file
			FileInputStream fstream = new FileInputStream(filepath);
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;

			JSONObject jsonObj = new JSONObject();
			int i = 0;

			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				if (strLine.contains("/dev/mapper/truecrypt")) {
					int start = strLine.indexOf(" ")+1;
					String mountpoint = strLine.substring(start);
					int end = mountpoint.indexOf(" ");
					mountpoint = mountpoint.substring(0, end);

					jsonObj.put(""+i, mountpoint);
					i++;
				}
			}

			result = jsonObj.toString();

			// Close the input stream
			in.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}

		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			IAMServer server = new AMServerImpl();

			System.out.println(server.getMountpoints());

			System.out.println("mount");

			System.out.println("result "+server.mount("/home/dradoslav/downloads/volume.tc", "/home/dradoslav/downloads/share", "ext4", "12345", ""));

			Thread.sleep(10000);

			System.out.println("unmount");

			System.out.println("result "+server.unmount("/home/dradoslav/downloads/share"));

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.exit(0);
	}

}